﻿Imports System.Data
Imports VSModel
Imports Cls_Common
Partial Class Control_Formula_MaterialSelect
    Inherits System.Web.UI.UserControl

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not Page.IsPostBack Then
            btnDelete.Attributes.Add("onclick", "return ComfirmDialog('Bạn có chắc chắn muốn Xóa nguyên liệu này không?', 0,'" + btnDelete.ClientID + "','0',1);")
            btnSelect.Attributes.Add("onclick", "javacript:setMaterialParentValues()")
            BindToGrid()
        End If
    End Sub
    Protected Sub btnDelete_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnDelete.Click
        Using Data As New VSEntities
            Dim i As Integer
            Dim intCount As Integer = 0
            Dim intTotal As Integer
            For i = 0 To lbxMaterial.Items.Count - 1
                If lbxMaterial.Items(i).Selected Then
                    intTotal += 1
                    Dim iMaterialId As Integer = lbxMaterial.Items(i).Value
                    Dim q = (From p In Data.Materials Where p.Id = iMaterialId Select p).FirstOrDefault
                    Try
                        Data.Materials.DeleteObject(q)
                        Data.SaveChanges()
                        intCount += 1
                    Catch ex As Exception
                    End Try
                End If
            Next
            If intCount > 0 Then
                Excute_Javascript("Alertbox('Xóa dữ liệu thành công. " & intCount.ToString & " /" & intTotal.ToString & " record.');", Me.Page, True)
                BindToGrid()
            Else
                Excute_Javascript("Alertbox('Xóa thất bại.');", Me.Page, True)
            End If
        End Using
    End Sub

    Protected Sub btnSave_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSave.Click
        Using Data As New VSEntities
            'Kiem tra tu khoa da ton tai chua
            Dim q = (From p In Data.Materials Where p.Title.ToUpper = txtMaterial.Text.Trim.ToUpper Select p).FirstOrDefault
            If (q Is Nothing) Then
                Dim mt As New Material
                mt.Title = txtMaterial.Text.Trim
                Data.Materials.AddObject(mt)
                Data.SaveChanges()
                mt = Nothing
                showError.Visible = False
                BindToGrid()
            Else
                showError.Visible = True
            End If
        End Using

    End Sub

    Private Sub BindToGrid()
        Using Data As New VSEntities
            Dim dt = (From q In Data.Materials Order By q.Title Ascending Select q)
            With lbxMaterial
                .DataSource = dt
                .DataTextField = "Title"
                .DataValueField = "Id"
                .DataBind()
            End With
            txtMaterial.Text = ""
        End Using
    End Sub
    
End Class
